﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SAKS.IServices;
using SAKS.Models;
using NHibernate;
using SAKS.Services.Query;

namespace SAKS.Services
{
    public class OrganizationServices : ServicesBase<Organization>, IOrganizationServices 
    {
        public override object[] List(int first, int pageSize, out int? totalRecords, string key)
        {
            var query = new PagedOrganizationSearch(Session) { First = first, PageSize = pageSize, Key = key };
            var result = query.Execute();
            totalRecords = result.TotalItems;
            var ret = from a in result.PageOfResults
                      select new string[]{
                          a.Id.ToString(),
                          a.Name,
                          a.ContactPerson,
                          a.Tel,
                          a.OrganizationType,
                          a.ProvinceMinistry,
                          a.Location,
                          a.Postalcode,
                          a.MailingAddress,
                          a.Email
                      };
            return ret.ToArray();
        }

        public override void Update(Organization o)
        {
            var org = Session.Get<Organization>(o.Id);
            Session.Delete(org);
            Session.Flush();
            Session.Save(o);
        }

        public Organization FindByName(string name)
        {
            var query = Session.QueryOver<Organization>().Where(o => o.Name == name);
            return query.SingleOrDefault();
        }

        public bool IsNameUserd(string name)
        {
            return 0 < Session.QueryOver<Organization>().Where(o => o.Name == name).ToRowCountQuery().FutureValue<int>().Value;
        }
    }
}
